package com.wxit.limit.optional;

import java.util.Optional;

public class OptionalTest {
    public static void main(String[] args) throws Exception {

        Student student = new Student("xiaohao", new Address("suqian"));
//        student = null;
        if (student != null) {
            String name = student.getName();
        }

        //直接判空，不推荐使用 代码冗余
        Optional<Student> student1 = Optional.ofNullable(student);
        if (student1.isPresent()) {
            System.out.println(student1.get().getName());
        }

        //推荐做法
        Optional.ofNullable(student).ifPresent(stu -> System.out.println(stu.getName()));

//        if (student != null) {
//            if (student.getAddress() != null) {
//                Address address = student.getAddress();
//                if (null != address.getCity()) {
//                    System.out.println(address.getCity());
//                }
//            }
//        }
//        throw new RuntimeException("有空值");

        Optional.ofNullable(student)
                .map(Student::getAddress)
                .map(Address::getCity)
                .orElseThrow(() -> new Exception("有控制"));


        OptionalTest optionalTest = new OptionalTest();
        Student student11 = optionalTest.getStudent1(student);
        System.out.println(student11);

        Student student2 = optionalTest.getStudent2(student);
        System.out.println(student2);
    }

    public Student getStudent1(Student student) {
        if (null != student) {
            String name = student.getName();
            if (name.equals("xiaohao")) {
                return student;
            }
            student = new Student();
            student.setName("xiaohao");
            return student;
        } else {
            student = new Student();
            student.setName("xiaohao");
            return student;
        }
    }

    public Student getStudent2(Student student) {
        return Optional.ofNullable(student)
                .filter(stu -> stu.getName().equals("xiaohao"))
                .orElseGet(() -> {
                    Student student1 = new Student();
                    student1.setName("wujie");
                    return student1;
                });
    }
}
